<template>
  <view
    class="drawer-wrapper"
    :class="{ active: visible }"
    @touchmove.stop.prevent
  >
    <!-- 遮罩层 -->
    <view
      class="drawer-mask"
      @click="maskClick ? close() : null"
      @touchmove.stop.prevent
    ></view>

    <!-- 抽屉内容 -->
    <view
      class="drawer-container"
      :class="{ open: visible }"
      :style="drawerStyle"
      @touchmove.stop
    >
      <view class="drawer-header">
        <text class="drawer-title">{{ title }}</text>
        <view class="drawer-close" @click="close">
          <uni-icons type="closeempty" size="24" color="#ffffff"></uni-icons>
        </view>
      </view>
      <!-- 当日期选择器或部门选择器激活时，使用普通 view -->
      <view
        v-if="datePickerActive || departmentPickerActive"
        class="drawer-content drawer-content-no-scroll"
        @touchmove.stop
      >
        <view class="search-form">
          <slot></slot>
        </view>
      </view>

      <!-- 正常情况下使用 scroll-view -->
      <scroll-view
        v-else
        scroll-y
        class="drawer-content"
        @touchmove.stop
        :show-scrollbar="true"
        enhanced
        :bounces="false"
      >
        <view class="search-form">
          <slot></slot>
        </view>
      </scroll-view>
      <view
        v-if="!datePickerActive && !departmentPickerActive"
        class="drawer-footer"
      >
        <button class="btn btn-reset" @click="handleReset">
          {{ resetText }}
        </button>
        <button class="btn btn-apply" @click="handleApply">
          {{ applyText }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from "vue";
// #ifdef APP-PLUS
import XenAppPicker from "./XenAppPicker.vue";
// #endif

// 定义组件属性
const props = withDefaults(
  defineProps<{
    title?: string;
    resetText?: string;
    applyText?: string;
    maskClick?: boolean;
    // 可以传入导航栏高度，如果没有传入则自动获取
    navbarHeight?: number;
  }>(),
  {
    title: "搜索条件",
    resetText: "重置",
    applyText: "应用搜索",
    maskClick: true,
    navbarHeight: 0,
  },
);

// 定义事件
const emit = defineEmits<{
  (e: "reset"): void;
  (e: "apply"): void;
  (e: "close"): void;
}>();

// 抽屉可见状态
const visible = ref(false);
// 日期选择器激活状态
const datePickerActive = ref(false);
// 部门选择器激活状态
const departmentPickerActive = ref(false);
// 顶部导航栏高度
const calculatedNavbarHeight = ref(0);
// 状态栏高度
const statusBarHeight = ref(0);

// 获取相关高度信息
onMounted(() => {
  // 获取系统信息
  try {
    const systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = systemInfo.statusBarHeight || 0;

    // 如果没有传入导航栏高度，尝试获取
    if (!props.navbarHeight) {
      // 默认导航栏高度 + 状态栏高度
      calculatedNavbarHeight.value = 40 + statusBarHeight.value;

      // 尝试获取实际导航栏高度
      setTimeout(() => {
        const pages = getCurrentPages();
        if (pages.length > 0) {
          const page = pages[pages.length - 1];
          uni
            .createSelectorQuery()
            .in(page)
            .select(".xen-navbar")
            .boundingClientRect((data: any) => {
              if (data) {
                calculatedNavbarHeight.value =
                  data.height || 40 + statusBarHeight.value;
              }
            })
            .exec();
        }
      }, 300);
    } else {
      calculatedNavbarHeight.value = props.navbarHeight;
    }
  } catch (e) {
    // 使用默认值
    statusBarHeight.value = 20;
    calculatedNavbarHeight.value = props.navbarHeight || 64; // 默认 44 + 20
  }
});

// 监听抽屉状态，处理页面滚动
watch(visible, (newVal) => {
  if (newVal) {
    // 打开抽屉时，禁止页面滚动
    // #ifdef H5
    try {
      const body = document.querySelector("body");
      if (body) {
        body.style.overflow = "hidden";
        body.style.position = "fixed";
        body.style.width = "100%";
      }
    } catch (e) {
      // 静默处理错误
    }
    // #endif
  } else {
    // 关闭抽屉时，恢复页面滚动
    // #ifdef H5
    try {
      const body = document.querySelector("body");
      if (body) {
        body.style.overflow = "";
        body.style.position = "";
        body.style.width = "";
      }
    } catch (e) {
      // 静默处理错误
    }
    // #endif
  }
});

// 计算抽屉样式
const drawerStyle = computed(() => {
  const navHeight = props.navbarHeight || calculatedNavbarHeight.value;
  return {
    top: `${navHeight}px`,
    height: `calc(100% - ${navHeight}px)`,
  };
});

// 打开抽屉
const open = () => {
  visible.value = true;
};

// 关闭抽屉
const close = () => {
  visible.value = false;
  nextTick(() => {
    emit("close");
  });
};

// 重置按钮处理
const handleReset = () => {
  emit("reset");

  // 关闭搜索面板
  close();

  // 提示重置成功
  uni.showToast({
    title: "重置成功",
    icon: "none",
  });
};

// 应用按钮处理
const handleApply = () => {
  emit("apply");
  close();
};

// 设置日期选择器状态
const setDatePickerActive = (active: boolean) => {
  datePickerActive.value = active;
};

// 设置部门选择器状态
const setDepartmentPickerActive = (active: boolean) => {
  departmentPickerActive.value = active;
};

// 暴露方法
defineExpose({
  open,
  close,
  setDatePickerActive,
  setDepartmentPickerActive,
});
</script>

<style lang="scss" scoped>
/* 抽屉包装容器 */
.drawer-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10;
  visibility: hidden;
  transition: visibility 0.3s;

  &.active {
    visibility: visible;
  }
}

/* 遮罩层 */
.drawer-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  opacity: 0;
  transition: opacity 0.3s;

  .active & {
    opacity: 1;
  }
}

/* 抽屉容器 */
.drawer-container {
  position: absolute;
  top: 0; /* 会被 drawerStyle 动态覆盖 */
  right: 0;
  width: 85%;
  max-width: 360px;
  height: 100%; /* 会被 drawerStyle 动态覆盖 */
  background-color: #ffffff;
  box-shadow: -4px 0 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  transform: translateX(100%);
  transition: transform 0.3s cubic-bezier(0.23, 1, 0.32, 1);
  will-change: transform;
  border-top-left-radius: 24px;
  border-bottom-left-radius: 24px;
  overflow: hidden;

  &.open {
    transform: translateX(0);
  }
}

/* 抽屉头部 */
.drawer-header {
  height: 50px; /* 减小高度 */
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px; /* 减小内边距 */
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  flex-shrink: 0;

  .drawer-title {
    font-size: 16px;
    font-weight: 600;
    color: #ffffff;
    margin-left: 10px;
  }

  .drawer-close {
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
  }
}

/* 抽屉内容 */
.drawer-content {
  flex: 1;
  // padding: 16px 16px; /* 减少内边距 */
  height: 0; /* 需要设置为0，否则会有滚动问题 */
  box-sizing: border-box;
  -webkit-overflow-scrolling: touch; /* 增加惯性滚动 */

  /* App端优化 */
  /* #ifdef APP-PLUS */
  /* 确保滚动区域在app端正常工作 */
  overflow-y: auto;
  /* #endif */
}

/* 无滚动版本的抽屉内容 - 用于日期选择器激活时 */
.drawer-content-no-scroll {
  overflow-y: auto;
  /* 确保不创建层叠上下文 */
  position: static;
  z-index: auto;
  contain: none;
  isolation: auto;
}

.search-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px 16px;
  box-sizing: border-box;
  gap: 12px; /* 增加表单项之间的间距 */
  padding-bottom: 20px; /* 增加底部间距 */
}

/* 抽屉底部 */
.drawer-footer {
  height: 60px; /* 减小高度 */
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  background-color: #ffffff;
  flex-shrink: 0;
  position: relative;
  z-index: 1;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);

  .btn {
    height: 38px; /* 减小按钮高度 */
    border-radius: 19px; /* 更新圆角 */
    font-size: 14px; /* 减小字体 */
    flex: 1;
    margin: 0 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;

    &:active {
      transform: scale(0.98);
      opacity: 0.9;
    }

    &.btn-reset {
      background-color: transparent;
      color: #6366f1;
      border: 1px solid #6366f1;
      position: relative;
      overflow: hidden;

      &::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(99, 102, 241, 0.08);
        transform: scaleX(0);
        transform-origin: right;
        transition: transform 0.3s ease;
        z-index: -1;
      }

      &:active::before {
        transform: scaleX(1);
        transform-origin: left;
      }
    }

    &.btn-apply {
      background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
      color: #ffffff;
      border: none;
      box-shadow: 0 4px 10px rgba(99, 102, 241, 0.3);
    }
  }
}

/* 确保日期选择器在抽屉中能正常显示 */
:deep(.uni-datetime-picker) {
  /* 确保日期选择器本身不创建层叠上下文 */
  position: static;
  z-index: auto;
}

/* 全局样式：确保日期选择器弹出层在抽屉之上 */

/* App端picker样式修复 */
/* #ifdef APP-PLUS */
:deep(.form-picker) {
  position: relative;
  z-index: 1;
}

:deep(.picker-content) {
  position: relative;
  z-index: 1;
}

/* 修复app端picker弹出层层级问题 */
:deep(.uni-picker-container) {
  z-index: 10002 !important;
}

:deep(.uni-picker-action) {
  z-index: 10002 !important;
}

:deep(.uni-picker-content) {
  z-index: 10002 !important;
}

/* 确保picker在抽屉中正常显示 */
.drawer-container :deep(.uni-picker-container),
.drawer-wrapper :deep(.uni-picker-container) {
  z-index: 10003 !important;
  position: fixed !important;
}
/* #endif */
</style>

<style lang="scss">
/* 全局样式：修复抽屉中的日期选择器层级问题 */
/* #ifdef MP-WEIXIN */
.drawer-wrapper .uni-datetime-picker__container-popup,
.drawer-container .uni-datetime-picker__container-popup {
  z-index: 10001 !important;
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
}

.drawer-wrapper .uni-datetime-picker__mask,
.drawer-container .uni-datetime-picker__mask {
  z-index: 10000 !important;
  position: fixed !important;
}
/* #endif */

/* App端全局picker样式修复 */
/* #ifdef APP-PLUS */
/* 修复app端picker在抽屉中的显示问题 */
.drawer-wrapper .uni-picker-container,
.drawer-container .uni-picker-container {
  z-index: 10003 !important;
  position: fixed !important;
}

.drawer-wrapper .uni-picker-action,
.drawer-container .uni-picker-action {
  z-index: 10003 !important;
}

.drawer-wrapper .uni-picker-content,
.drawer-container .uni-picker-content {
  z-index: 10003 !important;
}

/* 确保picker遮罩层正确显示 */
.drawer-wrapper .uni-picker-mask,
.drawer-container .uni-picker-mask {
  z-index: 10002 !important;
  position: fixed !important;
}
/* #endif */
</style>
